package com.excellent.CourseUtils;

import com.excellent.entity.ChatResponse;
import okhttp3.*;
import org.json.JSONException;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * 需要添加依赖
 * <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
 * <dependency>
 *     <groupId>com.squareup.okhttp3</groupId>
 *     <artifactId>okhttp</artifactId>
 *     <version>4.12.0</version>
 * </dependency>
 */

public class Chat {

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(100, TimeUnit.SECONDS)
            .readTimeout(100, TimeUnit.SECONDS)
            .build();

    public static void main(String[] args) {
        // 示例调用
        getAnswer("4511bdcb-f453-4e76-9882-c28108fb225b", "852a7413-7a7e-496b-8d2c-a08445a10c7e", "学习计划");
    }

    private static RequestBody createRequestBody(String appId, String conversationId, String question) {
        String json = String.format("{\"app_id\":\"%s\",\"query\":\"%s\",\"conversation_id\":\"%s\",\"stream\":false}",
                appId, question, conversationId);
        return RequestBody.create(MediaType.get("application/json; charset=utf-8"), json);
    }

    public static ChatResponse getAnswer(String appId, String conversationId, String question) {
        RequestBody body = createRequestBody(appId, conversationId, question);
        Request request = new Request.Builder()
                .url("https://qianfan.baidubce.com/v2/app/conversation/runs")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("X-Appbuilder-Authorization", "Bearer bce-v3/ALTAK-jnYex1wotKizobcUiYg8Z/ab021ae321c579d5ea3335f2eac029995a23de3e")
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful() || response.body() == null) {
                System.out.printf("从服务器获取回答失败: %d %s%n", response.code(), response.message());
                return null;
            }
            String res = response.body().string();
            System.out.printf("从服务器获取回答成功: %s%n", res);
            return ChatResponse.parse(res);
        } catch (IOException e) {
            System.err.println("请求过程中出现错误: " + e.getMessage());
            return null;
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}
